package com.hulei.studyproject.druid;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import java.util.Map;

/**
 * 动态切换数据源头
 * @Title: DynamicDataSource
 * @Description: TODO
 * @author: hulei
 * @date: 2023/8/3 10:10
 * @Version: 1.0
 */
@Slf4j
public class DynamicDataSource extends AbstractRoutingDataSource {

    public DynamicDataSource(DruidDataSource defaultDataSource, Map<Object,Object> targetDataSource){
          super.setDefaultTargetDataSource(defaultDataSource);
          super.setTargetDataSources(targetDataSource);
          super.afterPropertiesSet();
    }

    @Override
    protected Object determineCurrentLookupKey() {
        String dataSourceType = DynamicDataSourceContextHolder.getDataSourceType();
        //不打注解时,默认取主库
        if(dataSourceType == null || dataSourceType.isEmpty()){
            dataSourceType = DataSourceType.MASTER.name();
            log.info("使用默认数据库:{}",dataSourceType);
        }
        return dataSourceType;
    }
}
